package com.commerceE.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.commerceE.common.cache.EHCacheUtil;
import com.commerceE.common.exception.ServiceException;
import com.commerceE.common.search.BetweenPair;
import com.commerceE.common.search.ProductCriterion;
import com.commerceE.common.search.ProductSearch;
import com.commerceE.dao.CategoryDao;
import com.commerceE.dao.ProductDao;
import com.commerceE.domain.Category;
import com.commerceE.domain.Page;
import com.commerceE.domain.Products;
import com.commerceE.service.ImageService;
import com.commerceE.service.ProductService;
import com.commerceE.util.Constant;
import com.commerceE.vo.ProductSearchVo;

@Transactional
public class ProductServiceImpl implements ProductService {
	
	@Autowired
	private ProductDao productDao;
	
	@Autowired
	private CategoryDao categoryDao;
//	
//	@Autowired
//	private ProductInstanceDao productInstanceDao;
	
	@Autowired
	private ImageService imageService;
	
 
	/* (non-Javadoc)
	 * @see com.commerceE.service.ProductService#getAllListOfProduct()
	 */
	public List<Products> getAllListOfProduct() throws ServiceException{
		String key = "getAllListOfProduct";
		List<Products> productList = null;
		//Get data from cache according to the cache flag
		if(Constant.getEHCacheFlag()){
			productList = (List<Products>)EHCacheUtil.getFromProductCache(key);
		}
		if(productList==null){
			productList = productDao.getProductList();
			if(Constant.getEHCacheFlag()){
				EHCacheUtil.putToProductCache(key, productList);
			}
		}
		return productList;
	}
	
//	public List<Products> getAllListOfProductByConditions(ProductSearchVo productSearchVo) throws ServiceException{
//		List<Products> productList =  productDao.getAllListOfProductByConditions(productSearchVo);
//		for(Products product: productList){
//			product.setSmallImage(imageService.getProductSmallImage(product.getProductId()));
//			product.setBestBuyImage(imageService.getProductBestBuyImage(product.getProductId()));
//			product.setRegularImagelist(imageService.getProductRegularImage(product.getProductId()));
//		}
//		return productList;
//	}
	
	public List<Products> getAllListOfProductByConditions(ProductSearchVo productVO, Page page){
		String key = productVO.toString()+"-"+page.getItemSizePerPage()+"-"+page.getCurrentPageNum();
		List<Products> productList = null;
		if(Constant.getEHCacheFlag()){
			productList = (List<Products>)EHCacheUtil.getFromProductCache(key);
		}
		if(productList==null){
			ProductSearch productSearch = new ProductSearch();
			if(productVO.getCategoryIds()!=null && productVO.getCategoryIds().size()>0){
				List<Object> valueList = new ArrayList<Object>();
				for(Long categoryId :productVO.getCategoryIds()){
					valueList.add(new Long(categoryId));
				}
				ProductCriterion productCriterion = new ProductCriterion("categoryId",valueList);
				productCriterion.setValueListFlag(true);
				productSearch.addProductCriterion(productCriterion);
			}
			if(productVO.getPriceRangeStrs()!=null && productVO.getPriceRangeStrs().size()>0){
				List<BetweenPair> betweenPairList = new ArrayList<BetweenPair>();
				for(String priceRangeStr :productVO.getPriceRangeStrs()){
					String[] strs = priceRangeStr.split("-");
					Double startPrice = new Double(strs[0]);
					Double endPrice = new Double(strs[1]);
					betweenPairList.add(new BetweenPair(startPrice,endPrice));
				}
				ProductCriterion productCriterion = new ProductCriterion("discountPrice",betweenPairList,true);
				productCriterion.setOperation("<=");
				productSearch.addProductCriterion(productCriterion);
			}
			
			if(productVO.getGenders()!=null && productVO.getGenders().size()>0){
				List<String> genderList = productVO.getGenders();
				genderList.add("all");
				ProductCriterion productCriterion = new ProductCriterion("gender",genderList);
				productCriterion.setOperation("like");
				productCriterion.setValueListFlag(true);
				productSearch.addProductCriterion(productCriterion);
			}
			
			if(productVO.getOrderBy()!=null){
				if("".equals(productVO.getOrderBy().trim())){
					productVO.setOrderBy(null);
				}
			}
			
			
			if(page.getCurrentPageNum()<=0){
				page.setCurrentPageNum(1);
			}
			if(page.getItemSizePerPage()<=0){
				page.setItemSizePerPage(Page.DEFAULT_PAGE_SIZE);
			}
			int paginationStartFrom = page.getItemSizePerPage()*(page.getCurrentPageNum()-1);
			productSearch.setPaginationStartFrom(paginationStartFrom);
			productSearch.setItemSizePerPage(page.getItemSizePerPage());
			productSearch.setPageable(true);
			
			productSearch.setOrderByClause(productVO.getOrderBy());
			productList = productDao.selectByExample(productSearch);
			int totleSize = productDao.countByExample(productSearch);
			page.setTotleItemSize(totleSize);
			int totlePageSize = totleSize/page.getItemSizePerPage();
			if(totleSize%page.getItemSizePerPage()!=0){
				totlePageSize++;
			}
			page.setTotlePageSize(totlePageSize);
			for(Products product: productList){
				product.setSmallImage(imageService.getProductSmallImage(product.getProductId()));
				product.setBestBuyImage(imageService.getProductBestBuyImage(product.getProductId()));
				product.setRegularImagelist(imageService.getProductRegularImage(product.getProductId()));
			}
			if(Constant.getEHCacheFlag()){
				EHCacheUtil.putToProductCache(key, productList);
			}
		}
		return productList;
	}
	
	public List<Products> getProductListWithImage() throws ServiceException{
		String key = "getProductListWithImage";
		List<Products> productList = null;
		//Get data from cache according to the cache flag
		if(Constant.getEHCacheFlag()){
			productList = (List<Products>)EHCacheUtil.getFromProductCache(key);
		}
		if(productList==null){
			productList = productDao.getProductList();
			for(Products product: productList){
				product.setSmallImage(imageService.getProductSmallImage(product.getProductId()));
				product.setBestBuyImage(imageService.getProductBestBuyImage(product.getProductId()));
				product.setRegularImagelist(imageService.getProductRegularImage(product.getProductId()));
			}
			if(Constant.getEHCacheFlag()){
				EHCacheUtil.putToProductCache(key, productList);
			}
		}
		return productList;
	}
	
	public Products getProductWithImagesById(Long productId) throws ServiceException{
		String key = "getProductWithImagesById"+productId;
		Products product =  null;
		if(Constant.getEHCacheFlag()){
			product = (Products)EHCacheUtil.getFromProductCache(key);
		}
		if(product==null){
			product = getProductById(productId);
			if(product!=null){
				product.setRegularImagelist(imageService.getProductRegularImage(product.getProductId()));
				product.setSmallImage(imageService.getProductSmallImage(product.getProductId()));
				product.setCategory(categoryDao.get(product.getProductId()));
			}
			if(Constant.getEHCacheFlag()){
				EHCacheUtil.putToProductCache(key,product);
			}
		}
		return product;
	}
	
 
	/* (non-Javadoc)
	 * @see com.commerceE.service.ProductService#insertProduct(com.commerceE.domain.Product)
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertProduct(Products product) throws ServiceException{
//		try {
			productDao.insert(product);
//		} catch (DaoException e) {
//			throw new ServiceException(e.getExceptionCode(),e.getExceptionMessage());
//		}
	}
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateProduct(Products product) throws ServiceException{
		productDao.update(product);
	}
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void deleteProduct(Long productId) throws ServiceException{
		productDao.delete(productId);
	}
	
	
	public Products getProductById(Long productId) throws ServiceException{
		return productDao.get(productId);
//		try {
//			product = productDao.getProductById(productId);
//			if(product==null){
//				return null;
//			}else{
//				product.setProductionAttributeList(productInstanceDao.getProductAttributesByProductId(productId));
//				product.setProductionOptionList(productInstanceDao.getProductOptionListByProductId(productId));
//				product.setImageEntityList(imageDao.getImageEntityListByInstanceId(productId));
//				List<ProductInstance> productInstanceList = productInstanceDao.getProductInstanceListByProductId(productId);
//				int totleQuantity = 0;
//				for(ProductInstance productInstance:productInstanceList){
//					totleQuantity = totleQuantity+productInstance.getQuantity();
//				}
//				product.setProductInstanceList(productInstanceDao.getProductInstanceListByProductId(productId));
////				product.setTotleQuantity(productInstanceDao.getTotleQuantityOfProduct(productId));
//				product.setTotleQuantity(totleQuantity);
//			}
//		} catch (DaoException e) {
//			throw new ServiceException(e.getExceptionMessage());
//		}
	}


	public ProductDao getProductDao() {
		return productDao;
	}


	public void setProductDao(ProductDao productDao) {
		this.productDao = productDao;
	}


	public ImageService getImageService() {
		return imageService;
	}


	public void setImageService(ImageService imageService) {
		this.imageService = imageService;
	}
	
	

}
